<template>
	<section>
		<!--高级查询和新增按钮-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
<!--          输入的值会和在模型数据里的keyword双向绑定-->
					<el-input v-model="keyword" placeholder="请输入关键字" v-perm="'department:list'"></el-input>
				</el-form-item>
				<el-form-item>
<!--          querryKeyword 高级查询点击事件-->
					<el-button type="primary" v-on:click="querryKeyword" >查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-perm="'department:save'" @click="handleAdd" >新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="120" sortable>
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="150" >
			</el-table-column>
			<el-table-column prop="dirPath" label="部门路径" width="180" sortable>
			</el-table-column>
			<el-table-column prop="state" label="部门状态" width="150" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state==1">启用</span>
          <span style="color:red" v-else>禁用</span>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" width="120" sortable>
			</el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="150" sortable>
      </el-table-column>
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)" v-perm="'department:save'">编辑</el-button>
					<el-button type="danger" size="small" v-perm="'department:delete'" @click="hleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" v-perm="'department:pathchdel'">批量删除</el-button>
<!--      分页栏-->
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>


    <!--
      :title="title"  - 标题
      :visible.sync="saveFormVisible" - 是否显示对画框 - 默认不显示
      :close-on-click-modal="false" - 在对话框外面点击不关闭

      :model="saveForm"  -  绑定表单
      label-width="80px" -
      :rules="saveFormRules" - 表单的验证规则
      ref="saveForm" - 为当前对话框取名 - 方便验证表单
      prop="name" 绑定行类表单验证
    -->
<!--    添加和修改模态框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="100px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1" >启用</el-radio>
            <el-radio class="radio" :label="0" >禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
<!--          <el-input v-model="saveForm.manager_id" ></el-input>-->
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
<!--            v-for="item in managers" 遍历所有的员工-->
<!--            :label="item.username" 显示员工名字-->
<!--            :value="item.id" 传递数据id-->
            <el-option
                v-for="item in managers"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上级部门">
            <!--
            el-cascader - 级联
              :options="deptTree" - 级联框中需要的数据【集合】
            回显机制：
              v-model="saveForm.parent_id"
              parent：[2,5]
              deptTree:部门树
          -->
            <el-cascader v-model="saveForm.parent_id"
                         :options="deptTree"
                         :props="{
            	checkStrictly: true,
                label: 'name', // 级联框显示那个属性的值
                value: 'id'    // 回显时需要,回传值的时候也需要
            }" clearable>
            </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

	</section>
</template>

<script>
	export default {
		data() {
			return {
			  //当前页
        currentPage:1,
        //每页显示的条数
        pageSize:5,
        //总条数
        totals:30,
        //列表绑定值
        departments: [],
        //盲等框默认关闭
        listLoading: false,
        //高级查询
        keyword:"",
				sels: [],//列表选中列

				//编辑界面数据
				saveForm: {
          id: null,
          sn: '',
          name: '',
          state: 1,
          manager_id: null,
          parent_id: null
				},
        title:'',

				saveFormVisible: false,//编辑界面是否显示
				saveLoading: false,//盲等框
				saveFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' },
					],
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' },
          ]
				},
        managers:[],
        deptTree:[]
			}
		},
		methods: {
      //1.获取用户列表
      getdepartments() {
        let para = {
          'currentPage':this.currentPage,
          'pageSize':this.pageSize,
          'keyword': this.keyword
        };
        this.listLoading = true;
        this.$http.post("/department",para).then(result=>{
          this.departments=result.data.data;
          this.totals=result.data.totals;
          this.listLoading=false;
        }).catch(result=>{
          this.$message.error('系统繁忙,请稍后再试');
        })
      },
      // 页码变化事件
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getdepartments();
      },
      querryKeyword(){
      this.currentPage=1;
      this.getdepartments();
      },
			//删除
      hleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = { id: row.id };
					this.$http.delete("/department/"+row.id).then(result=>{
					  console.log(row.id)
            this.listLoading = false;
              if(result.data.success){
                let totalPage =Math.ceil(this.totals/this.pageSize);
                if(this.currentPage!=1 && this.currentPage==totalPage  && (this.totals-1)%this.pageSize==0){
                          this.currentPage=this.currentPage-1
                }
              }else {
                this.$message.error('删除失败500');
              }
            this.getdepartments()
            this.$message.success('删除成功');
          }).catch(result=>{
            this.$message.error('系统繁忙,请稍后再试400');
          })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.title= '修改'
        this.getManagers();
        this.getDeptTree();
				this.saveFormVisible = true;//打开模态框
				this.saveForm = Object.assign({}, row);  //回显数据：用数组接收,避免以前的数据发生改变
        console.log(this.saveForm)
			},
			//显示新增界面
			handleAdd: function () {
        this.title= '新增'
        this.getManagers();
        this.getDeptTree();
        this.saveFormVisible = true;
				this.saveForm = {
          id: null,
          sn: '',
          name: '',
          state: 1,
          manager_id: null,
          parent_id: null
				};
			},
			//新增和修改提交
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => { //表单验证
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.saveForm);
							//拿到模态框表单里的对象里的parent_id 数组
							var paras=para.parent_id;
							if(paras&&paras.length>0){//paras有数组并且数组长度大于0就拿到数组最后一个值为上级部门
							  para.parent_id=paras[paras.length-1];
              }
							if(paras.length==0){//如果为空数组
                para.parent_id=null;
              }
                this.$http.put("department",para).then(result=>{
                  this.saveFormVisible=false//编辑界面是否显示
                      this.saveLoading=false//盲等框
                  if(result.data.success){
                    this.$message.success('操作成功');
                    this.getdepartments();
                  }else {
                    this.$message.error('操作失败500');
                  }
                }).catch(result=>{
                  this.$message.error('操作失败400');
                })
						});
					}
				});
			},
      //选择批量删除会把当前行对象赋值给sels
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					//let para = { ids: ids };
					this.$http.patch("/department",ids).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						if(res.data.success){
              this.$message.success('删除成功');
              this.currentPage=1
              this.getdepartments();
            }else {
              this.$message.error('删除失败500');
            }
					}).catch(res=>{
            this.$message.error('删除失败400');
          });
				}).catch(() => {

				});
			},
      //查询
      getManagers(){
          this.$http.get("/employee").then(result=>{
              this.managers=result.data;
          })
      },
      //部门树
      getDeptTree(){
        this.$http.get("/department/deptTree").then(result=>{
          this.deptTree=result.data
        })
      }
		},
		mounted() {
			this.getdepartments();
		}
	}

</script>

<style scoped>

</style>